记录两个最近开发中遇到的两个问题
- iOS 11 下导航栏 item 会在 push 和 pop 的时候发生偏移问题
- Swift 中 UIButton 设置了 image 和 title 后,title 无法显示问题
问题描述
iOS 11 中导航栏在使用过程中 item 发生位置偏移,效果如图:

问题分析
- iOS 10 之前没有问题!
- 必须使用系统创建方式
- 两边 item 必须是使用同样的创建方式
基类中:XYNavigationController中
- 统一创建返回按钮,使用系统方法(从栈中的第二个VC开始)
- nav栈中首个VC,自己创建BackBtn(同样用系统方法)
分类中:UIBarButtonItem (XYAdd)
- 提供快速创建方法的 leftItem
- 提供快速创建方法的 rightItem
解决问题
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated { if (self.childViewControllers.count > 0) { viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationButtonReturn"] style:UIBarButtonItemStylePlain target:self action:@selector(back)]; viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor]; viewController.hidesBottomBarWhenPushed = YES; } [super pushViewController:viewController animated:animated]; } - (void)back{ [self popViewControllerAnimated:YES]; }
|
- 可定义 UIBarButtonItem 分类,快速创建 item,内部在iOS 11 下不可再用自定义 View 的方式
+ (UIBarButtonItem *)xy_itemWithTarget:(id)target action:(SEL)action title:(NSString *)title{ UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:title style:UIBarButtonItemStylePlain target:target action:action]; item.tintColor = [UIColor blackColor]; return item; }
|
Swift 中设置 title 和 不同状态 image ,title无法正常显示
Swift 下同时设置了UIButton 的 title 和 image ,title无法正确显示。
这应该是 Swift 的一个bug,项目中如果需要此功能,正确的实现方式应该是设置 Button 的不同状态下的背景图
optionBtn.setBackgroundImage(UIImage(named: "btn_image_normal"), for: .normal) optionBtn.setBackgroundImage(UIImage(named: "btn_answer_highlighted"), for: .highlighted) optionBtn.setTitle("按我", for: .normal) optionBtn.setTitle("按我", for: .highlighted) optionBtn.setTitleColor(UIColor.black, for: .normal) optionBtn.setTitleColor(UIColor.black, for: .highlighted)
|